package com.lottery.service.pc28.wealthService.impl;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

/**
 * 短信http接口的java代码调用示例
 * 基于Apache HttpClient 4.3
 * @since 2015-04-03
 */
public class JavaSmsApi {
   
    //模板发送接口的http地址
    private static String URI_TPL_SEND_SMS = "https://sms.yunpian.com/v2/sms/tpl_single_send.json";
 
    //编码格式。发送编码格式统一用UTF-8
    private static String ENCODING = "UTF-8";

    /**
     * 短信发送方法
     * @param phone
     * @return
     * @throws IOException
     */
    public static HashMap<String,String> getMessageStatus(String phone){
    	HashMap<String,String> m=new HashMap<String,String>();
        //模板发送的调用示例
		String sendSms="";
		try {
			//修改为您的apikey.apikey可在官网（http://www.yuanpian.com)登录后获取
			String apikey = "54ada7f9460127b8f13916b882a6956a";
			//修改为您要发送的手机号
			String mobile = URLEncoder.encode(phone,ENCODING);
			//设置您要发送的内容(内容必须和某个模板匹配。以下例子匹配的是系统提供的1号模板）
			String code = JavaSmsApi.getRandomString(4);
			m.put("code", code);
			String text = "【云片网】您的验证码是"+code;
			long tpl_id = 1;
			//设置对应的模板变量值
			String tpl_value = URLEncoder.encode("#code#",ENCODING) +"="
			    + URLEncoder.encode(code, ENCODING) + "&"
			    + URLEncoder.encode("#company#",ENCODING) + "="
			    + URLEncoder.encode("天安锐科",ENCODING);
			sendSms = JavaSmsApi.tplSendSms(apikey, tpl_id, tpl_value, mobile);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        m.put("sendSms", sendSms);
        return m;
       
    }

    
    
    
    /**
     * 通过模板发送短信
     * @param apikey    apikey
     * @param tpl_id    　模板id
     * @param tpl_value 　模板变量值
     * @param mobile    　接受的手机号
     * @return json格式字符串
     * @throws IOException
     */

    public static String tplSendSms(String apikey, long tpl_id, String tpl_value, String mobile) throws IOException {
        Map<String, String> params = new HashMap<String, String>();
        params.put("apikey", apikey);
        params.put("tpl_id", String.valueOf(tpl_id));
        params.put("tpl_value", tpl_value);
        params.put("mobile", mobile);
        return post(URI_TPL_SEND_SMS, params);
    }
    

   

  

   

    /**
     * 基于HttpClient 4.3的通用POST方法
     *
     * @param url       提交的URL
     * @param paramsMap 提交<参数，值>Map
     * @return 提交响应
     */

    public static String post(String url, Map<String, String> paramsMap) {
        CloseableHttpClient client = HttpClients.createDefault();
        String responseText = "";
        CloseableHttpResponse response = null;
        try {
            HttpPost method = new HttpPost(url);
            if (paramsMap != null) {
                List<NameValuePair> paramList = new ArrayList<NameValuePair>();
                for (Map.Entry<String, String> param : paramsMap.entrySet()) {
                    NameValuePair pair = new BasicNameValuePair(param.getKey(), param.getValue());
                    paramList.add(pair);
                }
                method.setEntity(new UrlEncodedFormEntity(paramList, ENCODING));
            }
            response = client.execute(method);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                responseText = EntityUtils.toString(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return responseText;
    }
	
	/**
	 * 
	 * @param length 表示生成字符串的长度  
	 * @return
	 */
	public static String getRandomString(int length) {
	    String base = "abcdefghijklmnopqrstuvwxyz0123456789";     
	    Random random = new Random();     
	    StringBuffer sb = new StringBuffer();     
	    for (int i = 0; i < length; i++) {     
	        int number = random.nextInt(base.length());     
	        sb.append(base.charAt(number));     
	    }     
	    return sb.toString();     
	 }
}
